<template>
  <!-- 分配角色数据权限对话框 -->
  <a-modal
    :ok-loading="submitDataScopeLoading"
    :title="dialog.title"
    :visible="dialog.visible"
    :width="480"
    cancel-text="取消"
    draggable
    ok-text="保存"
    title-align="start"
    @cancel="cancelDataScope"
    @ok="submitDataScope"
  >
    <a-spin :loading="dataScopeLoading" dot>
      <a-form ref="dataScopeRef" :model="form" :style="{ width: '440px' }" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item asterisk-position="end" field="roleName" label="角色名称" required validate-trigger="blur">
              <a-input v-model.trim="form.roleName" :disabled="true" allow-clear placeholder="请输入角色名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item asterisk-position="end" field="roleKey" label="权限字符" required validate-trigger="blur">
              <a-input v-model.trim="form.roleKey" :disabled="true" allow-clear placeholder="请输入权限字符" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item asterisk-position="end" field="dataScope" label="权限范围" required validate-trigger="blur">
              <a-select v-model="form.dataScope" placeholder="请选择权限范围" @change="dataScopeSelectChange">
                <a-option v-for="item in dataScopeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-show="form.dataScope === '2'" :gutter="16">
          <a-col :span="24">
            <a-form-item field="dataScope" label="数据权限" validate-trigger="blur">
              <a-tree
                ref="deptRef"
                v-model:checked-keys="checkedKeys"
                :check-strictly="!form.deptCheckStrictly"
                :data="deptOptions"
                :field-names="{
                  key: 'id',
                  title: 'label',
                  children: 'children'
                }"
                checkable
                class="tree-border"
                show-line
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" name="Role" setup>
import { DeptTreeOption, RoleVO } from "@/api/system/role/types";
import { dataScope, deptTreeSelect, getRole } from "@/api/system/role";
const dialog = reactive<DialogOption>({
  visible: false,
  title: ""
});
/** 数据范围选项*/
const dataScopeOptions = ref([
  { value: "1", label: "全部数据权限" },
  { value: "2", label: "自定数据权限" },
  { value: "3", label: "本部门数据权限" },
  { value: "4", label: "本部门及以下数据权限" },
  { value: "5", label: "仅本人数据权限" }
]);

const dataScopeLoading = ref(false);
const submitDataScopeLoading = ref(false);
const multiple = ref(true);
const form = reactive({
  roleId: undefined,
  roleSort: 1,
  roleStatus: "0",
  roleName: "",
  roleKey: "",
  menuCheckStrictly: true,
  deptCheckStrictly: true,
  remark: "",
  dataScope: "1",
  menuIds: [],
  deptIds: []
});

const dataScopeRef = ref<ArcoFormInstance>();
const deptRef = ref<ArcoTreeInstance>();
const checkedKeys = ref([]);
const deptOptions = ref<DeptTreeOption[]>([]);

/** 所有部门节点数据 */
const getDeptAllCheckedKeys = (): any => {
  // 目前被选中的部门节点
  let checkedKeys = deptRef.value?.checkedKeys;
  // 半选中的部门节点
  let halfCheckedKeys = deptRef.value?.halfCheckedKeys;
  if (halfCheckedKeys) {
    checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
  }
  return checkedKeys;
};

/** 提交按钮（数据权限） */
const submitDataScope = async () => {
  submitDataScopeLoading.value = true;
  try {
    if (form.roleId) {
      form.deptIds = getDeptAllCheckedKeys();
      await dataScope(form);
      dialog.visible = false;
    }
  } finally {
    submitDataScopeLoading.value = false;
  }
};

/** 取消按钮（数据权限）*/
const cancelDataScope = () => {
  dataScopeRef.value?.resetFields();
  dialog.visible = false;
};

/** 根据角色ID查询部门树结构 */
const getRoleDeptTreeSelect = async (roleId: string | number) => {
  const res = await deptTreeSelect(roleId);
  deptOptions.value = res.data.depts;
  return res.data;
};

/** 分配数据权限操作 */
const show = async (row: RoleVO) => {
  dialog.visible = true;
  dialog.title = "分配数据权限";
  try {
    dataScopeLoading.value = true;
    const response = await getRole(row.roleId);
    const res = await getRoleDeptTreeSelect(row.roleId);
    await nextTick(() => {
      deptRef.value?.internalSetCheckedKeys(res.checkedKeys);
    });
    Object.assign(form, response.data);
  } finally {
    dataScopeLoading.value = false;
  }
};

/** 选择角色权限范围触发 */
const dataScopeSelectChange = (value: string) => {
  if (value !== "2") {
    deptRef.value?.internalSetCheckedKeys([]);
  }
};

/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
};

defineExpose({
  show
});
</script>
<style lang="less" scoped>
.tree-border {
  border: 1px solid #e5e6e7;
  margin-top: 5px;
  border-radius: 4px;
  width: 100%;
  height: 150px;
  overflow-y: scroll;
}
</style>
